// DsmTimeClient.cc
// author: CASO-04

#include "TcpListener.h"
#include "Dsm.h"

#define BUFFER_SIZE 1024

void usage()
{
	cout << "Usage: DsmTimeClient <dsm-server-port> <servername>" << endl;
	exit(1);
}


int main(int argc, char** argv)
{
	if (argc != 3)
	{
		usage();
	}

	// Hacer lookup dsm.deusto.es 
	PracticaCaso::DsmDriver * driver = new PracticaCaso::DsmDriver("127.0.0.1", atoi(argv[1]), argv[2]);
	PracticaCaso::DsmData data;
	
	// Leer memoria	
	while (true)
	{
		try
		{
			data = driver->dsm_get("GLOBAL_TIMESTAMP");
		}
		catch (DsmException dsme)
		{
			cerr << "ERROR in dsm_get(\"GLOBAL_TIMESTAMP\") - waiting for other process to initialize it: " << dsme << endl;
			driver->dsm_wait("GLOBAL_TIMESTAMP");
		}
		
		string s = "";
		/*for(int i = 0; i<3; i++)
		{
			s += *((char *)(data.addr+i));
		}*/
		for(int i = 0; i<data.size; i++)
		{
			s += ((char *)(data.addr))[i];
			if ((((char *)(data.addr))[i]) == '\0')
				break;
		}
		//char * lectura = (char *)(data.addr);
		/*for(int i =1; i<5; i++)
		{
			cout << lectura[i];
		}*/
		
		//cout << "***TIME: " << *((char *)data.addr) << "***" << endl;
		
		cout << s << endl;
		
		sleep(1);
	}
	
	cout << "Sleeping for a second before finishing ..." << endl;
	sleep(1);
	delete driver;
}

